//
//  HomeViewController.m
//  JKScanTool
//
//  Created by jike on 16/5/20.
//  Copyright © 2016年 YM. All rights reserved.
//

#import "HomeViewController.h"
#import "TabObject.h"
#import "HomeProductCell.h"
#import "ScanedProductCell.h"
#import "ZBarScanVC.h"
@interface HomeViewController ()<UIPageViewControllerDataSource,UIPageViewControllerDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UIPageViewController *_pageViewCtrl;//
    UIScrollView *_bgView;//无数据的背景提示
    NSMutableArray *_dataArray;//专题数据源
    NSMutableArray *_dataArray1;//数据源2222...
    CGFloat _btnW;//上面滚动项宽度
    UIView *_lineView;
    NSInteger _currentPage;//当前页
    UIView *_backEditView;
    UIView *_editView;
    UIView *_backTView;//背景提示view
    NSString * _urlIndex;//起始页
    NSString *_totalCount;//总页数
    BOOL _isLoading;
    FeWifiManHub *_loading; //菊花
    NSString *_proID;
    NSIndexPath *_indexPath;
}
@property(nonatomic,strong)UITableView *tableView;
@end

@implementation HomeViewController

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (void)viewWillAppear:(BOOL)animated {
    if (_searchUrl.length != 0 || [_HaveScaned isEqualToString:@"YES"]) {
        if ([[AppData share].scanSuccess2Refresh isEqualToString:@"isScanSuccess"]) {
            if ([[AppData share].searchType isEqualToString:@"2"]) {//已扫码产品
                [self RefreshRowWithIndexPath:_indexPath];
            }else {
                if (_indexPath.row < _dataArray.count) {
                    [_dataArray removeObjectAtIndex:_indexPath.row];
                    [_tableView reloadData];
                }
            }
            [AppData share].scanSuccess2Refresh = @"";
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    if (_searchUrl.length != 0 || [_HaveScaned isEqualToString:@"YES"]) {
        [self registerForKeyboardNotifications];
        [self SetUpMainTableView];//创建tableview
        [self setUpEditView];
        [self loadData];//加载数据
        if ([_HaveScaned isEqualToString:@"YES"]) {
            [self setUpBackViewWithImage:@"noOrder" tips:@"暂无相关产品"];
        }else {
            [self setUpBackViewWithImage:@"noSearch" tips:@"搜索结果为空"];
        }
    }else {
        [self initNav:@"商品分类" isLeftItem:YES isRightSearch:YES];
        [self createUI2];
    }
}
#pragma mark -- SEARCH.. 2222222
- (void)SetUpMainTableView {
    self.view.backgroundColor = BackColor;
    if ([_HaveScaned isEqualToString:@"YES"]) {
        [self initNav:@"已扫码商品" isLeftItem:YES isRightSearch:YES];
    }else {
        [self initNav:@"搜索结果" isLeftItem:YES isRightSearch:YES];
    }
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    _tableView.footer = footer;
    [self.view addSubview:_tableView];
    _dataArray1 = [[NSMutableArray alloc]init];
    _urlIndex = @"1";
    _isLoading = NO;
    _proID = @"";
    _loading = [[FeWifiManHub alloc] initWithView:[UIApplication sharedApplication].keyWindow withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y , _loading.frame.size.width, _loading.frame.size.height);
    [[UIApplication sharedApplication].keyWindow addSubview:_loading];
    [_loading show];
}
#pragma mark -- 上啦加载
- (void)loadMore {
    if (_isLoading) {
        if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
            [_tableView.footer noticeNoMoreData];
            [_tableView.footer endRefreshing];
        }
        return;
    }
    _isLoading = YES;
    if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
        [_tableView.footer noticeNoMoreData];
        [_tableView.footer endRefreshing];
        return;
    }
    _urlIndex  = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
    [self loadData];
}
#pragma mark -- 下拉刷新
- (void)refreshData {
    if (_isLoading) {
        return;
    }
    _urlIndex = @"1";
    _isLoading = YES;
    [self loadData];
}

- (void)loadData {//已扫码..
    NSString * kurl;
    if ([_HaveScaned isEqualToString:@"YES"]) {
        kurl = [NSString stringWithFormat:ScanedProductUrl,@"15",_urlIndex];
    }else {//搜索..
        //        //搜索...未扫码
        //#define ScanSearchGoodUrl BaseUrl @"/WPT-OpenAPI?control=ShopCommon&action=SearchProdByPrdName&pagesize=%@&pageIndex=%@&sign=%@&prdname=%@"
        //        //搜索..已扫码
        //#define ScanedSearchGoodUrl BaseUrl @"/WPT-OpenAPI?control=ShopCommon&action=SearchScanedProd&pagesize=%@&pageIndex=%@&prdname=%@"
        if ([AppData share].searchType.length == 0) {
            [AppData share].searchType = @"1";
        }
        if ([[AppData share].searchType isEqualToString:@"1"]) {//1.未扫码产品，2.已扫码产品
            kurl = [NSString stringWithFormat:ScanSearchGoodUrl,@"15",_urlIndex,[Utils md5SignStr],_searchUrl];
        }else if ([[AppData share].searchType isEqualToString:@"2"]){//已扫码
            kurl = [NSString stringWithFormat:ScanedSearchGoodUrl,@"15",_urlIndex,_searchUrl];
        }
    }
    if ([_urlIndex isEqualToString:@"1"]) {
        if (_dataArray1.count > 0) {
            [_dataArray1 removeAllObjects];
        }
    }
    [AFNetworkHandler GETWithAFNByURL:kurl completion:^(id result) {
        NSDictionary * dic = result;
        if ([dic[@"r"] isEqualToString:@"T"]) {
            NSArray *arr = [dic objectForKey:@"d"];
            [_dataArray1 addObjectsFromArray:arr];
        }
        _totalCount = [dic objectForKey:@"totalPage"];
        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        _isLoading = NO;
        [_loading dismiss];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_tableView reloadData];
    }];
}
#pragma mark --刷新指定行..
- (void)RefreshRowWithIndexPath:(NSIndexPath *)indexPath {
    NSString * kurl;
    if ([_HaveScaned isEqualToString:@"YES"]) {
        kurl = [NSString stringWithFormat:ScanedProductUrl,@"1",[NSString stringWithFormat:@"%ld",indexPath.row + 1]];
    }else {//搜索..
        if ([AppData share].searchType.length == 0) {
            [AppData share].searchType = @"1";
        }
        if ([[AppData share].searchType isEqualToString:@"1"]) {//1.未扫码产品，2.已扫码产品
            kurl = [NSString stringWithFormat:ScanSearchGoodUrl,@"1",[NSString stringWithFormat:@"%ld",indexPath.row + 1],[Utils md5SignStr],_searchUrl];
        }else if ([[AppData share].searchType isEqualToString:@"2"]){//已扫码
            kurl = [NSString stringWithFormat:ScanedSearchGoodUrl,@"1",[NSString stringWithFormat:@"%ld",indexPath.row + 1],_searchUrl];
        }
    }
    [AFNetworkHandler GETWithAFNByURL:kurl completion:^(id result) {
        NSDictionary * dic = result;
        if ([dic[@"r"] isEqualToString:@"T"]) {
            NSArray *arr = [dic objectForKey:@"d"];
            [_dataArray1 replaceObjectAtIndex:indexPath.row withObject:[arr firstObject]];
        }
        [_tableView reloadData];
    }];
}
- (void)setUpBackViewWithImage:(NSString *)image tips:(NSString *)tip {
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [_tableView addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:image];//@"noSearch"
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = tip;//@"抱歉，没有找到相关订单"
    [_backTView addSubview:label];
}

#pragma mark -- 编辑视图
- (void)setUpEditView {
    _backEditView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    _backEditView.backgroundColor = SetColor(0, 0, 0, 0.3);
    _backEditView.hidden = YES;
    UITapGestureRecognizer *tapG = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(endEdit)];
    [_backEditView addGestureRecognizer:tapG];
    [[UIApplication sharedApplication].keyWindow addSubview:_backEditView];
    //编辑视图
    _editView = [[UIView alloc]initWithFrame:CGRectMake(15, (ScreenHeight - 132)/2, ScreenWidth - 30, 132)];
    _editView.backgroundColor = [UIColor whiteColor];
    [_backEditView addSubview:_editView];
    _editView.layer.cornerRadius = 5;
    _editView.layer.masksToBounds = YES;
    
    for (int i = 0;i < 2; i++) {
        UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 44 * i, ScreenWidth - 20, 44)];
        textField.borderStyle = UITextBorderStyleNone;
        textField.font = [UIFont systemFontOfSize:13];
        textField.tag = 1000 + i;//100,101,
        if (i == 1) {
            textField.placeholder = @"请输入13位有效的条形码";
            textField.delegate = self;
            textField.keyboardType = UIKeyboardTypeDecimalPad;
            
        }else {
            textField.enabled = NO;
        }
        [_editView addSubview:textField];
        
        //lineView
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0,44 + 44 * i, _editView.frame.size.width,0.5)];
        lineView.backgroundColor = SetColor(0, 0, 0, 0.2);
        [_editView addSubview:lineView];
    }
    //保存按钮
    NSArray *titleArr = @[@"取消",@"保存"];
    for (int i = 0; i < 2; i++) {
        UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sureBtn.frame = CGRectMake(15 + (_editView.frame.size.width - 30)/2 *i, 88, (_editView.frame.size.width - 30)/2, 44);
        [sureBtn setTitle:titleArr[i] forState:UIControlStateNormal];
        sureBtn.tag = 120 + i;
        [sureBtn setTitleColor:MainColor forState:UIControlStateNormal];
        [_editView addSubview:sureBtn];
        [sureBtn addTarget:self action:@selector(sureBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
}
#pragma mark -- 保存
-(void)sureBtnClicked:(UIButton *)sender
{
    if (sender.tag == 120) {//取消
        [self endEdit];
    }else if (sender.tag == 121){
        UITextField *titleT = (UITextField *)[_backEditView viewWithTag:1001];
        NSString *str = titleT.text;
        if (str.length == 13) {
            if (![Utils isConnectionAvailable]) { //断网
                [[MessShowView share] showWithMess:@"断网了啦"];
            }else{
                [self sendCode:str];
            }
        }else{
            [[MessShowView share] showWithMess:@"请输入正确的条形码"];
        }
    }
}
#pragma mark ---上传条码
-(void)sendCode:(NSString *)str
{
    _loading = [[FeWifiManHub alloc] initWithView:[UIApplication sharedApplication].keyWindow withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 64, _loading.frame.size.width, _loading.frame.size.height);
    [[UIApplication sharedApplication].keyWindow addSubview:_loading];
    [_loading show];
    
    NSString *kUrl;
    kUrl = [NSString stringWithFormat:UpLoadInformation,[AppData share].realLoginName,str,_proID];
    [AFNetworkHandler GETWithAFNByURL:kUrl completion:^(id result) {
        NSDictionary *dic = result;
        NSString *result1 = [dic objectForKey:@"m"];
        if ([result1 isEqualToString:@"success"]) {
            [_loading dismiss];
            [[MessShowView share] showWithMess:@"上传成功啦"];
            [UIView animateWithDuration:0.5 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self endEdit];
            } completion:nil];
            if ([_HaveScaned isEqualToString:@"YES"] || [[AppData share].searchType isEqualToString:@"2"]) {//已扫码和搜索已扫码
                [self RefreshRowWithIndexPath:_indexPath];
            }else {//搜索未扫码商品
                if (_indexPath.row < _dataArray1.count) {
                    [_dataArray1 removeObjectAtIndex:_indexPath.row];
                    [_tableView reloadData];
                }
            }
        }else{
            [_loading dismiss];
            [[MessShowView share] showWithMess:@"上传失败"];
        }
    }];
}
- (void)endEdit {
    _editView = [[UIView alloc]initWithFrame:CGRectMake(15, (ScreenHeight - 132)/2, ScreenWidth - 30, 132)];
    _backEditView.hidden = YES;
    [_backEditView endEditing:YES];
    [_editView endEditing:YES];
}
#pragma mark -- 移除通知
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];//移除全部通知。
}
#pragma mark -- 添加监听
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
#pragma mark -- 键盘高度
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    if (_searchUrl.length != 0 || [_HaveScaned isEqualToString:@"YES"]) {
        NSDictionary *info = [notification userInfo];
        CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
        CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
        CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
        CGRect inputFieldRect = _editView.frame;
        if (inputFieldRect.origin.y + 132 > ScreenHeight + yOffset) {//遮挡..
            CGFloat offset= (inputFieldRect.origin.y + 132 - (ScreenHeight + yOffset));
            inputFieldRect.origin.y -= offset;
            [UIView animateWithDuration:duration animations:^{
                _editView.frame = inputFieldRect;
            }];
        }
    }
}

#pragma mark --tableview DELEGATE..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray1.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0001;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"homecell";
    static NSString *scanedIdenti = @"scanedcell";
    if ([_HaveScaned isEqualToString:@"YES"] || [[AppData share].searchType isEqualToString:@"2"]) {//已扫码...
        ScanedProductCell *cell = [tableView dequeueReusableCellWithIdentifier:scanedIdenti];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ScanedProductCell" owner:nil options:nil] firstObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.scanBtn addTarget:self action:@selector(BtnClick:WithEvent:) forControlEvents:UIControlEventTouchUpInside];
        [cell.editBtn addTarget:self action:@selector(BtnClick:WithEvent:) forControlEvents:UIControlEventTouchUpInside];
        if (indexPath.row < [_dataArray1 count]) {
            [cell.iconImageView sd_setImageWithURL:[_dataArray1[indexPath.row] objectForKey:@"img"] placeholderImage:[UIImage imageNamed:@"fanglanmao"]];
            cell.titleLabel.text = [_dataArray1[indexPath.row] objectForKey:@"name"];
            cell.numLabel.text = [NSString stringWithFormat:@"条码:%@",[_dataArray1[indexPath.row] objectForKey:@"barCode"]];
            NSDictionary *dic = [[_dataArray1[indexPath.row] objectForKey:@"properties"] firstObject];
            cell.descLabel.text = [dic objectForKey:@"propertyname"];
            cell.proceLabel.text = [dic objectForKey:@"saleprice"];
        }
        return cell;
    }else {//未扫码..
        HomeProductCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"HomeProductCell" owner:nil options:nil] firstObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.scanBtn addTarget:self action:@selector(BtnClick:WithEvent:) forControlEvents:UIControlEventTouchUpInside];
        [cell.editBtn addTarget:self action:@selector(BtnClick:WithEvent:) forControlEvents:UIControlEventTouchUpInside];
        if (indexPath.row < [_dataArray1 count]) {
            [cell.iconImageView sd_setImageWithURL:[_dataArray1[indexPath.row] objectForKey:@"img"] placeholderImage:[UIImage imageNamed:@"fanglanmao"]];
            cell.titleLabel.text = [_dataArray1[indexPath.row] objectForKey:@"name"];
            NSDictionary *dic = [[_dataArray1[indexPath.row] objectForKey:@"properties"] firstObject];
            cell.descLabel.text = [dic objectForKey:@"propertyname"];
            cell.priceLabel.text = [dic objectForKey:@"saleprice"];
            
        }
        return cell;
    }
}
- (void)BtnClick:(UIButton *)sender WithEvent:(id)event {
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_tableView];
    NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];
    _indexPath = indexPath;
    UITextField *titleT = (UITextField *)[_backEditView viewWithTag:1000];
    UITextField *numT = (UITextField *)[_backEditView viewWithTag:1001];
    if (indexPath!= nil)
    {
        if (sender.tag == 10) {
            ZBarScanVC *scanVC = [[ZBarScanVC alloc]init];
            if (_indexPath.row < [_dataArray1 count]) {
                scanVC.productId = [_dataArray1[indexPath.row] objectForKey:@"id"];
                }
            [self.navigationController pushViewController:scanVC animated:YES];
        }else if (sender.tag == 11){
            if (indexPath.row < [_dataArray1 count]) {
                titleT.text = [_dataArray1[indexPath.row] objectForKey:@"name"];
                _proID = [_dataArray1[indexPath.row] objectForKey:@"id"];
            }
            numT.text = @"";
            numT.placeholder = @"请输入13位有效的条形码";
            _backEditView.hidden = NO;
        }
    }
}

#pragma mark -- MAINHome..1111111
#pragma mark -- 创建加载网络数据后的头标题UI
- (void)createUI2{
    _dataArray = [NSMutableArray array];
    _bgView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 35)];
    _bgView.showsHorizontalScrollIndicator = NO;
    _bgView.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:_bgView];
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 98, ScreenWidth, 0.5)];
    lineView.backgroundColor = [UIColor lightGrayColor];
    lineView.alpha = 0.5;
    [self.view addSubview:lineView];
    NSString *kUrl;
    kUrl = [NSString stringWithFormat:CateGoryUrl,[Utils md5SignStr]];
    NSMutableArray *Marr =[[NSMutableArray alloc]init];
    NSMutableArray *Farr=[[NSMutableArray alloc]init];
    [AFNetworkHandler GETWithAFNByURL:kUrl completion:^(id result) {
        NSDictionary *dic = result;
        if ([dic[@"r"] isEqualToString:@"T"]) {
            [_loading dismiss];//菊花消失..
            NSArray * MainArr = [dic objectForKey:@"d"];
            NSInteger index;
            if (_CurrentIndex.length == 0) {
                index = 0;
            }else {
                index = [_CurrentIndex integerValue];
            }
            NSDictionary *dicc = MainArr[index];///取2级分类数据源..
            NSArray *arr = [dicc objectForKey:@"children"];
            if (arr) {
                [Marr addObject:@"全部"];
                for (int i = 0; i < arr.count; i++) {
                    [Marr addObject:[arr[i]objectForKey:@"name"]];
                    [Farr addObject:[arr[i]objectForKey:@"id"]];
                }
                //刷新标题
                NSString *titleStr;
                if (_MainTitle.length == 0) {
                    titleStr = [[MainArr firstObject] objectForKey:@"name"];
                }else {
                    titleStr = _MainTitle;
                }
                [self initNav:titleStr doBack:NO];
                
                //主ID
                NSString *mainID;
                if (_MainCID.length == 0    ) {
                    mainID = [[MainArr firstObject] objectForKey:@"id"];
                }else {
                    mainID = _MainCID;
                }
                
                //总数据源
                NSUserDefaults *userDefaults2 = [NSUserDefaults standardUserDefaults];
                [userDefaults2 setObject:MainArr forKey:@"MainArr"];//1级
                [userDefaults2 synchronize];
                
                //2级分类
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:Farr forKey:@"TType"];//2级分类
                [userDefaults synchronize];
                NSUserDefaults *userDefaults1 = [NSUserDefaults standardUserDefaults];
                
                
                //2级标题
                [userDefaults1 setObject:Marr forKey:@"TTitle"];//2级标题
                [userDefaults1 synchronize];
                NSArray *array = Marr;
                for(int i=0;i<array.count;i++){
                    TabObject *tab = [[TabObject alloc]init];
                    tab.title = array[i];
                    tab.subViewController = [[HomeSubController alloc]init];
                    tab.subViewController.currentPage = i;
                    tab.subViewController.MainID = mainID;
                    [_dataArray addObject:tab];
                    __weak typeof(self)wSelf = self;
                    [tab.subViewController setMyBlock:^(UIViewController *sub) {
                        [wSelf.navigationController pushViewController:sub animated:YES];
                    }];
                }
                _currentPage = 0;
                _lineView = [[UIView alloc]init];
                _lineView.backgroundColor = MainColorOld;
                [_bgView addSubview:_lineView];
                _btnW = 0;
                for(int i=0;i<_dataArray.count;i++){
                    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                    btn.frame = CGRectMake(i*70, 0, 70, 35);
                    [btn setTitle:array[i] forState:UIControlStateNormal];;
                    btn.backgroundColor = [UIColor orangeColor];
                    [btn setTitleColor:SetColor(51, 51, 51, 1) forState:UIControlStateNormal];
                    btn.titleLabel.font = [UIFont systemFontOfSize:13];
                    //btn长度和位置计算
                    CGSize size = [btn.titleLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:btn.titleLabel.font,NSFontAttributeName, nil]];
                    btn.frame = CGRectMake(23*(i + 1) + _btnW, 0, size.width, 35);
                    _btnW += size.width;
                    [btn setTitleColor:MainColor forState:UIControlStateSelected];
                    [btn setBackgroundColor:[UIColor clearColor]];
                    [btn addTarget:self action:@selector(changeTab:) forControlEvents:UIControlEventTouchUpInside];
                    btn.tag = 100 + i;
                    [_bgView addSubview:btn];
                    if(i==0){
                        btn.selected = YES;
                        _lineView.frame = CGRectMake(btn.frame.origin.x, 28, btn.frame.size.width, 2);
                    }
                }
                _bgView.contentSize =CGSizeMake(23*(_dataArray.count + 1) + _btnW, 0);
                [self configPageViewController];
                //            //[self createCollctionViewUI];
            }else {
                UIView *noNetView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64)];
                
                noNetView.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:243 / 255.0 blue:247 / 255.0 alpha:1];
                [self.view addSubview:noNetView];
                UIImageView *netImg = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenWidth-100)/2, 60, 100, 90)];
                netImg.image = [UIImage imageNamed:@"无网络_r1_c1"];
                [noNetView addSubview:netImg];
                UILabel *netFail = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, ScreenWidth, 20)];
                netFail.text = @"网络请求失败";
                netFail.textAlignment = NSTextAlignmentCenter;
                netFail.font = [UIFont systemFontOfSize:16];
                [noNetView addSubview:netFail];
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight - 150);
                //[btn addTarget:self action:@selector(noNetBtnClick) forControlEvents:UIControlEventTouchUpInside];
                [noNetView addSubview:btn];
                [self.view addSubview:noNetView];
            }
            //            [_loading dismiss];
            //            [_loading removeFromSuperview];
        }
    }];
    
}
- (void)configPageViewController{
    _pageViewCtrl = [[UIPageViewController alloc]initWithTransitionStyle:(UIPageViewControllerTransitionStyleScroll) navigationOrientation:(UIPageViewControllerNavigationOrientationHorizontal) options:nil];
    HomeSubController * sub = [_dataArray[_currentPage] subViewController];
    
    [_pageViewCtrl setViewControllers:@[sub] direction:(UIPageViewControllerNavigationDirectionForward) animated:YES completion:^(BOOL finished) {
        
        
    }];
    _pageViewCtrl.view.frame = CGRectMake(0, 35+64, ScreenWidth, ScreenHeight-35-64);
    [self.view addSubview:_pageViewCtrl.view];
    _pageViewCtrl.dataSource = self;
    _pageViewCtrl.delegate = self;
    //获取显示所有view的滚动视图
    UIScrollView *sv = _pageViewCtrl.view.subviews[0];
    sv.delegate = self;
    [_pageViewCtrl.view.subviews[0] setDelegate:self];
}
//单击按钮时切换视图
- (void)changeTab:(UIButton *)sender {
    NSInteger index = sender.tag-100;
    HomeSubController *sub = [_dataArray[index] subViewController];
    
    __weak typeof(_bgView)wBgView = _bgView;
    __weak typeof(_lineView)wLineView = _lineView;
    //显示翻页后要显示sub，翻页方向根据单击的按钮决定
    [_pageViewCtrl setViewControllers:@[sub] direction:_currentPage>index animated:YES completion:^(BOOL finished) {
        _currentPage = index;
        for(UIView *view in wBgView.subviews){
            if([view isKindOfClass:[UIButton class]]){
                UIButton *tb = (UIButton *)view;
                if(tb.tag == sender.tag){
                    tb.selected=YES;
                }else {
                    tb.selected = NO;
                }}}
        wLineView.frame = CGRectMake(sender.frame.origin.x, 28, sender.frame.size.width, 2);
    }];
    if ((16*(_dataArray.count + 1) + _btnW) > ScreenWidth) {
        //点击按钮滚动到中间
        CGFloat offsetX = sender.center.x - 3*ScreenWidth/8;
        if (offsetX < 0) { // 处理最小滚动偏移量
            offsetX = 0;
        }
        CGFloat maxOffsetX = _bgView.contentSize.width - ScreenWidth;
        if (offsetX > maxOffsetX) { // 处理最大滚动偏移量
            offsetX = maxOffsetX;
        }
        [_bgView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    }
}
#pragma mark --
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    HomeSubController *sub = (HomeSubController *)viewController;
    NSInteger index = sub.currentPage;
    index++;
    if(index>=_dataArray.count){
        index = 0;
        return nil;
    }
    HomeSubController *rsvc = [_dataArray[index]subViewController];
    return rsvc;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
    HomeSubController *sub = (HomeSubController *)viewController;
    NSInteger index = sub.currentPage;
    index--;
    if(index<0){
        index = _dataArray.count-1;
        return nil;
    }
    HomeSubController *rsvc = [_dataArray[index]subViewController];
    return rsvc;
    
}
//翻页成功后执行的方法
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{
    HomeSubController *sub = (HomeSubController *)pageViewController.viewControllers[0];
    _currentPage = sub.currentPage;
    for(UIView *view in _bgView.subviews){
        if([view isKindOfClass:[UIButton class]]){
            UIButton *btn = (UIButton *)view;
            if(btn.tag-100==_currentPage){
                btn.selected =YES;
            }else {
                btn.selected = NO;
            }
        }
    }
    UIButton *btn = (UIButton *)[_bgView viewWithTag:_currentPage + 100];
    _lineView.frame = CGRectMake(btn.frame.origin.x, 28, btn.frame.size.width, 2);
    if ((16*(_dataArray.count + 1) + _btnW) > ScreenWidth) {
        //点击按钮滚动到中间
        CGFloat offsetX = btn.center.x - 3*ScreenWidth/8;
        if (offsetX < 0) { // 处理最小滚动偏移量
            offsetX = 0;
        }
        CGFloat maxOffsetX = _bgView.contentSize.width - ScreenWidth;
        if (offsetX > maxOffsetX) { // 处理最大滚动偏移量
            offsetX = maxOffsetX;
        }
        [_bgView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    }
}
#pragma mark ---UITextField代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField.tag == 1001) {//条码
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        if (toBeString.length > 13) {
            
            return NO;
            
        }else{
            
            //  判断输入的是否为数字 (只能输入数字)
            NSString *validRegEx =@"^[0-9]*$";
            NSPredicate *regExPredicate =[NSPredicate predicateWithFormat:@"SELF MATCHES %@", validRegEx];
            BOOL myStringMatchesRegEx = [regExPredicate evaluateWithObject:string];
            if (myStringMatchesRegEx){
                return YES;
            }else{
                return NO;
            }
        }
        
        
    }else{
        
        return NO;
    }
}


@end
